<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :title="title"
      :destroyOnClose="true"
      :width="modalWidth"
      @cancel="handleClose"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="handleOk" type="primary">确认</a-button>
        </div>
      </template>
      <a-spin :spinning="confirmLoading">
        <a-form-model ref="ruleForm" :model="model" :rules="rules">
          <div class="formBox">
            <div class="requiredNews">生产计划信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="计划单号"
                  prop="planNum"
                  hasFeedback
                >
                  <a-input
                    :disabled="disabled"
                    placeholder="请输入计划单号"
                    v-model.trim="model.planNum"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="商品"
                  hasFeedback
                  prop="goodsId"
                >
                  <a-select
                    :open="false"
                    :defaultOpen="false"
                    mode="multiple"
                    :allowClear="true"
                    placeholder="关联商品"
                    v-model.trim="model.goodsId"
                    :disabled="disabled"
                    @dropdownVisibleChange="
                      (open) =>
                        handleTableSelect(open, 'goodsId', 'tableModal', '商品')
                    "
                    @change="
                      (value) => handleChange(value, 'goodsId', goodModel)
                    "
                  >
                    <a-select-option
                      v-for="item in goodModel.tableOption"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.goodsName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="计划数量"
                  hasFeedback
                  prop="planQuantity"
                >
                  <a-input-number
                    :disabled="disabled"
                    style="width:100%"
                    placeholder="请输入计划数量"
                    v-model.trim="model.planQuantity"
                    :min="1"
                    :max="99999999"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="开始时间"
                  hasFeedback
                  prop="planStartTime"
                >
                  <a-date-picker
                    :showToday="false"
                    placeholder="请选择开始时间"
                    @change="
                      (date, dateString) =>
                        onChange(date, dateString, 'planStartTime')
                    "
                    v-model.trim="model.planStartTime"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="计划完成时间"
                  hasFeedback
                  prop="planEndTime"
                >
                  <a-date-picker
                    :showToday="false"
                    placeholder="请选择计划完成时间"
                    @change="
                      (date, dateString) =>
                        onChange(date, dateString, 'planEndTime')
                    "
                    v-model.trim="model.planEndTime"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="最终入库时间"
                  hasFeedback
                >
                  <a-date-picker
                    :showToday="false"
                    placeholder="请选择最终入库时间"
                    :disabled="disabled"
                    @change="
                      (date, dateString) =>
                        onChange(date, dateString, 'finalWarehouseEnrtyTime')
                    "
                    v-model.trim="model.finalWarehouseEnrtyTime"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <!-- line-1 -->
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="销售订单编号"
                  hasFeedback
                  prop="orderId"
                >
                  <a-select
                    :open="false"
                    :defaultOpen="false"
                    mode="multiple"
                    :allowClear="true"
                    placeholder="请选择销售订单"
                    v-model.trim="model.orderId"
                    :disabled="disabled"
                    @dropdownVisibleChange="
                      (open) =>
                        handleTableSelect(
                          open,
                          'orderId',
                          'tableSaleModal',
                          '销售订单'
                        )
                    "
                    @change="
                      (value) => handleChange(value, 'orderId', saleModel)
                    "
                  >
                    <a-select-option
                      v-for="item in saleModel.tableOption"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.orderNumber }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="客户"
                  hasFeedback
                >
                  <a-select
                    :open="false"
                    :defaultOpen="false"
                    mode="multiple"
                    :allowClear="true"
                    placeholder="请选择客户"
                    v-model.trim="model.customId"
                    disabled
                  >
                    <a-select-option
                      v-for="item in customerModel.tableOption"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.customerName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="备注"
                  hasFeedback
                >
                  <a-input
                    placeholder="请输入备注"
                    v-model.trim="model.remark"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
          <div class="formBox" v-if="tableData.length > 0">
            <div class="requiredNews">商品信息</div>
            <a-table :data-source="tableData" :columns="columns"></a-table>
          </div>
        </a-form-model>
        <!-- 商品选择 -->
        <TableSelectModal
          :columns="goodModel.columns"
          :replaceFields="goodModel.replaceFields"
          :treeKey="goodModel.treeKey"
          :tableKey="goodModel.tableKey"
          :searchKey="goodModel.searchKey"
          :name="goodModel.name"
          :code="goodModel.code"
          :filename="goodModel.filename"
          ref="tableModal"
          @tableSelect="tableSelect"
        ></TableSelectModal>
        <!-- 销售订单选择 -->
        <TableSelectModal
          :columns="saleModel.columns"
          :replaceFields="saleModel.replaceFields"
          :treeKey="saleModel.treeKey"
          :tableKey="saleModel.tableKey"
          :searchKey="saleModel.searchKey"
          :name="saleModel.name"
          :code="saleModel.code"
          :filename="saleModel.filename"
          ref="tableSaleModal"
          @tableSelect="tableSaleSelect"
        ></TableSelectModal>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import api from "@/api/apiServer";
import TableSelectModal from "@/components/TableSelectModal";
import { goodColumns } from "@/pages/ProductionPlan/components/tableConfig";
import { saleColumns } from "@/pages/OrderMent/components/tableConfig";
import moment from "moment";
export default {
  components: { TableSelectModal },
  props: {
    disabled: {
      type: Boolean,
    },
  },
  data() {
    return {
      title: "", // 标题
      visible: false, // 状态、
      modalWidth: 1460, // 抽屉宽度
      model: {},
      show: true, //根据菜单类型，动态显示隐藏表单元素
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      measureOption: [], // 计量单位
      productOption: [], // 产品编号
      orderOption: [], // 销售订单
      customerOption: [], // 客户
      columns: goodColumns,

      // 商品选中组件参数
      goodModel: {
        replaceFields: {
          children: "goodsTypeList",
          title: "goodsTypeName",
          key: "id",
          value: "id",
        },
        treeKey: "CommodityTypeFindAll",
        tableKey: "CommodityList",
        searchKey: "goodsType",
        name: "goodsName",
        code: "goodsCode",
        filename: "CommodityModal",
        columns: goodColumns,
        tableOption: [],
      },
      saleModel: {
        replaceFields: {},
        tableKey: "orderPageList",
        code: "orderNumber",
        filename: "OrderMentModal",
        columns: saleColumns,
        tableOption: [],
      },
      customerModel: {
        tableOption: [],
      },
      // 当前选中产品
      checkResult: {},
      tableData: [],
    };
  },
  computed: {
    rules() {
      return {
        planNum: [
          { required: true, message: "请输入计划单号", trigger: "blur" },
        ],
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        planQuantity: [
          { required: true, message: "请输入计划数量", trigger: "change" },
        ],
        planStartTime: [
          { required: true, message: "请选择开始时间", trigger: "change" },
        ],
        planEndTime: [
          { required: true, message: "请选择计划完成时间", trigger: "change" },
        ],
      };
    },
  },
  methods: {
    // 处理选择组件的数据
    setData(result, tableOption, modelName, key) {
      this[modelName].tableOption = tableOption;
      if (modelName === "goodModel") {
        this.checkResult = result[0];
      }
      if (this[modelName].mode) {
        let arr = result.map((item) => {
          return item.id;
        });
        this.$set(this.model, key, arr);
      } else {
        this.$set(this.model, key, result[0].id);
      }
      this.$refs.ruleForm.clearValidate([key]);
    },
    // 商品选择
    tableSelect(result, tableOption) {
      this.setData(result, tableOption, "goodModel", "goodsId");
    },
    // 销售订单选择
    tableSaleSelect(result, tableOption) {
      if (result.length > 0) {
        this.$set(this.model, "customId", result[0].customer);
        this.getCustomerAllList();
        this.setData(result, tableOption, "saleModel", "orderId");
      }
    },
    // 商品选择
    handleTableSelect(open, key, refName, name) {
      this.$refs[refName].title = name;
      this.$refs[refName].modalAdd();
      if (this.model[key]) {
        let arr = this.model[key].toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs[refName].selectedRowKeys = newArr;
        } else {
          this.$refs[refName].selectedRowKeys = [];
        }
      }
    },
    // 事件选择回调
    handleChange(value, key, model) {
      if (value.length > 0) {
        if (model.mode) {
          this.model[key] = value;
        } else {
          this.model[key] = value.toString();
        }
      } else {
        this.model[key] = null;
      }
    },
    // 获取商品数据
    async getProductList(key, value) {
      let params = { pageNumber: 1, pageSize: 10, deleteFlag: "N" };
      if (value) {
        params[key] = value;
        const res = await api.CommodityList(params);
        this.goodModel.tableOption = res.data.data;
      }
    },
    // 获取销售订单数据
    async getOrderPageList(key, value) {
      let params = { pageNumber: 1, pageSize: 10 };
      if (value) {
        params[key] = value;
        const res = await api.orderPageList(params);
        this.saleModel.tableOption = res.data.data;
      }
    },
    // 获取客户数据
    async getCustomerAllList() {
      let params = { pageNumber: 1, pageSize: 999999, deleteFlag: "N" };
      const res = await api.customerPageList(params);
      this.customerModel.tableOption = res.data.data;
    },
    // 获取计划单号
    async getProductPlanNum() {
      const res = await api.ProductPlanNum({ type: "parent", code: "JH" });
      this.$set(this.model, "planNum", res.data);
    },
    // 获取数据来源
    async getDictFindByCode(parentCode, key) {
      const res = await api.DictFindByCode({ parentCode });
      this[key + "Option"] = res.data;
    },
    onChange(date, dateString, key) {
      this.$set(this.model, key, dateString);
    },
    // 新增
    modalAdd() {
      this.$set(
        this.model,
        "planStartTime",
        moment(new Date())
          .subtract(0, "days")
          .format("YYYY-MM-DD")
      );
      this.$set(
        this.model,
        "planEndTime",
        moment(new Date())
          .subtract(0, "days")
          .format("YYYY-MM-DD")
      );
      this.modalEdit(this.model);
      this.getProductPlanNum();
    },
    // 编辑
    modalEdit(record) {
      this.resetScreenSize();
      this.visible = true;
      this.getProductList("id", record.goodsId);
      this.getOrderPageList("id", record.orderId);
      this.getCustomerAllList();
      this.getDictFindByCode("dict.measure", "measure");
      if (record.goodsId) {
        this.getCommodityList(record.goodsId);
      }
      this.model = Object.assign({}, record);
      if (this.model.customId == null) {
        delete this.model.customId;
      }
      if (this.model.orderId == null) {
        delete this.model.orderId;
      }
    },
    //通过id获取商品列表的数据
    async getCommodityList(id) {
      let params = {
        pageNumber: 1,
        pageSize: 10,
        id,
        deleteFlag: "N",
      };
      const res = await api.CommodityList(params);
      this.tableData = res.data.data;
      this.checkResult = res.data.data[0];
    },
    // 关闭
    handleClose() {
      this.visible = false;
      this.model = Object.assign({});
      this.tableData = [];
      this.$refs.ruleForm.resetFields();
    },

    async submitVulFun() {
      this.confirmLoading = true;
      const res = await api.ProductPlanUpdate(this.model);
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      const that = this;
      if (res.data !== 0 && this.title == "新增生产计划") {
        that.confirmLoading = false;
        that.$emit("ok");
        that.visible = false;
        let { goodsId, planNum } = this.model;
        that.$confirm({
          title: "提示",
          content: "该商品存在下级商品,是否生成下级生产计划?",
          okText: "确认",
          cancelText: "取消",
          onOk() {
            that.setProductPlanSon({ goodsId, planNum, pid: res.data });
          },
          onCancel() {},
        });
        that.model = Object.assign({});
      } else {
        that.confirmLoading = false;
        that.$message.success(res.message);
        that.$emit("ok");
        that.visible = false;
        that.model = Object.assign({});
      }
      this.tableData = [];
    },
    // 生成子生产计划
    async setProductPlanSon(params) {
      const res = await api.ProductPlanSon(params);
      this.$message.success(res.message);
      this.$emit("ok");
    },
    async handleOk() {
      const that = this;
      // 触发表单验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (that.title === "编辑子生产计划") {
            that.submitVulFun();
          } else {
            if (that.checkResult.isUsedBom == 1) {
              that.submitVulFun();
            } else {
              that.$message.error("当前商品未生产bom,请先生产bom");
            }
          }
        } else {
          return false;
        }
      });
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.modalWidth = screenWidth;
      } else {
        this.modalWidth = 1460;
      }
    },
  },
};
</script>

<style lang="less">
.formBox {
  width: 100%;
  border: 1px solid #e9e9e9;
  padding: 10px 16px;
  margin: 18px 0;
  .requiredNews {
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    color: #1a5eff;
    margin-bottom: 12px;
  }

  .ant-calendar-picker {
    width: 100%;
  }
}
</style>
